<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\admin\model\Themes;
use app\admin\validate\Config as ConfigValidate;
use app\admin\model\Config as ConfigModel;
/**
 * 配置管理
 */
class Config extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        // 基础
        $basics = ConfigModel::getVal('basics');
        // 邮箱
        $email  = ConfigModel::getVal('email');
        // 用户
        $user   = ConfigModel::getVal('user');
        // 主题
        $themes = ConfigModel::getVal('themes');
        // 用户额外配置
        $userHook = [];
        foreach (event("UserConfigHook") as $key => $val) {
            foreach ($val as $k => $v) {
                array_push($userHook, $v);
            }
        }
        if (! empty($userHook)) {
            foreach ($userHook as $k => $v) {
                $userHook[$k]['value'] = isset($user[$v['field']]) ? $user[$v['field']] : $v['value'];
            }
        }
        // 额外配置
        $hook    = [];
        foreach (event("ConfigHook") as $key => $val) {
            foreach ($val as $k => $v) {
                array_push($hook, $v);
            }
        }
        // 上传
        $upload = [];
        $upload['admin'] = include(root_path() . 'app/admin/config/upload.php');
        $upload['index'] = include(root_path() . 'app/index/config/upload.php');
        View::assign([
            'basics'   => (object)$basics,
            'email'    => (object)$email,
            'user'     => (object)$user,
            'upload'   => $upload,
            'themes'   => $themes,
            'userHook' => $userHook,
            'hook'     => $hook,
        ]);
        return View::fetch();
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            validate(ConfigValidate::class)->check($input);
            if ($input['type'] === 'theme') {
                // 主题
                $name   = 'theme_' . $input['name'] . '_' . $this->request->lang;
                $themes = Themes::field('config, title')->where('name', $input['name'])->find();
                $value  = [];
                foreach ($input['value'] as $key => $val) {
                    $value[$val['field']] = $val['value'];
                }
                $themes->config = $input['value'];
                $themes->save();
                cache('themes_' . $input['name'], NULL);
                ConfigModel::setVal($name, $input['title'], $value);
            } else {
                $value = $input['value'];
                switch ($input['name']) {
                    case 'upload':
                        file_put_contents(root_path().'app/index/config/upload.php', "<?php\nreturn ".var_export($value['index'],true).";");
                        file_put_contents(root_path().'app/admin/config/upload.php', "<?php\nreturn ".var_export($value['admin'],true).";");
                        break;
                    case 'user':
                        $value = [];
                        foreach ($input['value'] as $key => $val) {
                            $value[$val['field']] = $val['value'];
                        }
                        ConfigModel::setVal($input['name'],$input['title'], $value);
                        break;
                    default:
                        ConfigModel::setVal($input['name'],$input['title'], $value);
                        break;
                }
            }
            return json(['status' => 'success', 'message' => '操作成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 链接配置
     */
    public function link()
    {
        $input = input();
        $data  = [];
        if (isset($input['table'])){
            // 搜索条件
            foreach ($input['search'] as $key => $val) {
                if ($key === 'language') {
                    $where[] = ['language', '=', $this->request->lang];
                } else {
                    $where[] = [$key, '=', $val];
                }
            }
            // 关键词匹配
            if (isset($input['keyword']) && ! empty($input['keyword'])) {
                $where[] = ['title', 'like', '%'.$input['keyword'].'%'];
            }
            $exist = Db::query("SHOW TABLES LIKE 'mk_".$input['table']."'");
            if ($exist) {
                $data = Db::name($input['table'])->where($where)->limit(20)->select();
            }
        } else {
            foreach (plugin_route('link') as $key => $value) {
                if ($value['type'] === 'single') {
                    array_push($data, $value);
                }
            }
        }
        return json(['status' => 'success', 'message' => '', 'data' => $data]);
    }
}
